﻿using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.Common;
using Casamiel.Domain.Response;
using MediatR;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Casamiel.Application.Commands.HappinessTree
{
	/// <summary>
	/// Get rewards command handler.
	/// </summary>
	public sealed class GetRewardsCommandHandler : BaseCommandHandler, IRequestHandler<GetRewardsCommand, BaseResult<string>>
	{
		private readonly IMemberCardService _cardService;
		/// <summary>
		/// Initializes a new instance of the
		/// </summary>
		/// <param name="IMemberCardService"></param>
		/// <param name="netICService">Net ICS ervice.</param>
		/// <param name="httpClientFactory">Http client factory.</param>
		/// <param name="settings">Settings.</param>
		public GetRewardsCommandHandler(IMemberCardService cardService, INetICService netICService, IHttpClientFactory httpClientFactory, IOptionsSnapshot<CasamielSettings> settings) : base(netICService, httpClientFactory, settings)
		{
			_cardService = cardService;
		}

		/// <summary>
		/// Handle the specified request and cancellationToken.
		/// </summary>
		/// <returns>The handle.</returns>
		/// <param name="request">Request.</param>
		/// <param name="cancellationToken">Cancellation token.</param>
		public async Task<BaseResult<string>> Handle(GetRewardsCommand request, CancellationToken cancellationToken)
		{
			if (request == null) {
				throw new ArgumentNullException(nameof(request));
			}
			var data = new { request.RewardId, request.Mobile };
			var rsp = await PostThirdApiAsync<String>("v3/HappyTree/CanReceiveReward", JsonConvert.SerializeObject(data)).ConfigureAwait(false);
			if (rsp.Code == 0) {
				var cardInfo = await _cardService.GetBindCardAsync<ICasaMielSession>(request.Mobile).ConfigureAwait(false);
				if (cardInfo == null) {
					return new BaseResult<string>("", -37, "没有会员卡");
				}
				var icreq = new Domain.Request.IC.AddTicketsReq {
					Cardno = cardInfo.CardNO,
					Phoneno = request.Mobile,
					Largesstickets = new System.Collections.Generic.List<Domain.Request.IC.Ticket>()
				};

				if (DateTime.Now > DateTime.Parse("2019-7-12", System.Globalization.CultureInfo.CurrentCulture)) {
					//幸福蛋糕树专享优惠券-满50元立减10元
					icreq.Largesstickets.Add(new Domain.Request.IC.Ticket {
						Ticketid = 589247,
						Ticketnum = 1,
						Ticketprice = 10
					});

				} else {
					//幸福蛋糕树专享优惠券-满50元立减20元
					icreq.Largesstickets.Add(new Domain.Request.IC.Ticket {
						Ticketid = 589168,
						Ticketnum = 1,
						Ticketprice = 20
					});
				}

				var result = await base.NetICService.Icticketlargess(icreq).ConfigureAwait(false);
				OrderLogger.Trace($"GetRewardsCommand-icticketlargesscancel,req:{JsonConvert.SerializeObject(icreq)},rsp:{JsonConvert.SerializeObject(result)}");
				if (result.code == 0) {
					var jjobj = JsonConvert.DeserializeObject<JObject>(result.content);
					var Largessno = jjobj["largessno"].ToString();
					var req = new { request.RewardId, request.Mobile, CouponId = Largessno, Type = 0 };
					var response = await PostThirdApiAsync<String>("v3/HappyTree/ChangeRewardStatus", JsonConvert.SerializeObject(req)).ConfigureAwait(false);
					if (response.Code == 0) {
						return new BaseResult<string>("", 0, "领取成功");
					} else {
						var creq = new Domain.Request.IC.TicketLargessCancelReq { Largessno = Largessno };
						var re = await NetICService.Icticketlargesscancel(creq).ConfigureAwait(false);
						OrderLogger.Error($" GetRewardsCommand-icticketlargesscancel,req:{JsonConvert.SerializeObject(creq)}，rsp:{JsonConvert.SerializeObject(re)}");
						return new BaseResult<string>("", 999, "领取失败");
					}
				} else {
					return new BaseResult<string>("", result.code, result.msg);
				}

			}
			return rsp;
		}

	}
}
